// ==UserScript==
// @name         kimi聊天文字显示优化
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  优化KIMI聊天界面的文字显示效果，提供文本大小、行高和内容宽度的调整功能
// @author       You
// @match        https://www.kimi.com/chat*
// @grant        GM_addStyle
// @grant        GM_setValue
// @grant        GM_getValue
// @run-at       document-end
// ==/UserScript==

(function() {
    'use strict';

    // 添加样式
    GM_addStyle(`
        #text-control-panel {
            position: fixed;
            top: 20px;
            right: 20px;
            background-color: rgba(255, 255, 255, 0.8);
            border-radius: 10px;
            padding: 15px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
            z-index: 9999;
            transition: all 0.3s ease;
            width: 300px;
        }
        
        #text-control-panel.collapsed {
            width: 40px;
            height: 40px;
            padding: 0;
            border-radius: 50%;
            background-color: #3498db;
            display: flex;
            justify-content: center;
            align-items: center;
            cursor: pointer;
        }
        
        #text-control-panel.collapsed .panel-content {
            display: none;
        }
        
        #text-control-panel .circle-icon {
            display: none;
            color: white;
            font-size: 20px;
            font-weight: bold;
        }
        
        #text-control-panel.collapsed .circle-icon {
            display: block;
        }
        
        .slider-container {
            margin-bottom: 15px;
        }
        
        .slider-container label {
            display: block;
            margin-bottom: 5px;
            font-size: 14px;
            color: #333;
        }
        
        .slider-container input {
            width: 100%;
        }
        
        .slider-value {
            float: right;
            font-weight: bold;
        }
        
        /* 修改聊天内容区域的样式 */
        .chat-content-container {
            width: 100% !important;
            max-width: 100% !important;
        }
        
        /* 聊天内容列表样式 */
        .chat-content-list {
            width: 100% !important;
            max-width: 100% !important;
        }
        
        /* 段落容器样式 */
        .segment-container {
            width: 100% !important;
            max-width: 100% !important;
        }
        
        /* 内容盒子样式 */
        .segment-content-box {
            width: 100% !important;
            max-width: 100% !important;
        }
        
        /* Markdown容器样式 */
        .markdown-container {
            width: 100% !important;
            max-width: 100% !important;
        }
        
        /* 表格容器样式 */
        .table-container {
            width: 100% !important;
            max-width: 100% !important;
        }
        
        /* 思考部分的文字颜色设置为灰色 */
        .segment-generate-tip {
            color: #777 !important;
        }
    `);

    // 保存设置到存储
    function saveSettings(fontSize, lineHeight, contentWidth) {
        GM_setValue('kimi_fontSize', fontSize);
        GM_setValue('kimi_lineHeight', lineHeight);
        GM_setValue('kimi_contentWidth', contentWidth);
        console.log('设置已保存:', {fontSize, lineHeight, contentWidth});
    }
    
    // 从存储加载设置
    function loadSettings() {
        const defaultSettings = {
            fontSize: '16',
            lineHeight: '1.5',
            contentWidth: '100'
        };
        
        const settings = {
            fontSize: GM_getValue('kimi_fontSize', defaultSettings.fontSize),
            lineHeight: GM_getValue('kimi_lineHeight', defaultSettings.lineHeight),
            contentWidth: GM_getValue('kimi_contentWidth', defaultSettings.contentWidth)
        };
        
        console.log('加载设置:', settings);
        return settings;
    }

    // 创建控制面板
    function createControlPanel() {
        const panel = document.createElement('div');
        panel.id = 'text-control-panel';
        
        const circleIcon = document.createElement('div');
        circleIcon.className = 'circle-icon';
        circleIcon.textContent = 'A';
        panel.appendChild(circleIcon);
        
        const panelContent = document.createElement('div');
        panelContent.className = 'panel-content';
        
        // 加载保存的设置
        const savedSettings = loadSettings();
        
        // 文本大小滑块
        const fontSizeContainer = document.createElement('div');
        fontSizeContainer.className = 'slider-container';
        
        const fontSizeLabel = document.createElement('label');
        fontSizeLabel.innerHTML = `文本大小: <span class="slider-value">${savedSettings.fontSize}px</span>`;
        
        const fontSizeSlider = document.createElement('input');
        fontSizeSlider.type = 'range';
        fontSizeSlider.min = '5';
        fontSizeSlider.max = '45';
        fontSizeSlider.step = '2';
        fontSizeSlider.value = savedSettings.fontSize;
        
        fontSizeContainer.appendChild(fontSizeLabel);
        fontSizeContainer.appendChild(fontSizeSlider);
        
        // 行高滑块
        const lineHeightContainer = document.createElement('div');
        lineHeightContainer.className = 'slider-container';
        
        const lineHeightLabel = document.createElement('label');
        lineHeightLabel.innerHTML = `行高: <span class="slider-value">${savedSettings.lineHeight}</span>`;
        
        const lineHeightSlider = document.createElement('input');
        lineHeightSlider.type = 'range';
        lineHeightSlider.min = '0.5';
        lineHeightSlider.max = '5';
        lineHeightSlider.step = '0.2';
        lineHeightSlider.value = savedSettings.lineHeight;
        
        lineHeightContainer.appendChild(lineHeightLabel);
        lineHeightContainer.appendChild(lineHeightSlider);
        
        // 内容宽度滑块
        const contentWidthContainer = document.createElement('div');
        contentWidthContainer.className = 'slider-container';
        
        const contentWidthLabel = document.createElement('label');
        contentWidthLabel.innerHTML = `内容宽度: <span class="slider-value">${savedSettings.contentWidth}%</span>`;
        
        const contentWidthSlider = document.createElement('input');
        contentWidthSlider.type = 'range';
        contentWidthSlider.min = '50';
        contentWidthSlider.max = '100';
        contentWidthSlider.step = '2';
        contentWidthSlider.value = savedSettings.contentWidth;
        
        contentWidthContainer.appendChild(contentWidthLabel);
        contentWidthContainer.appendChild(contentWidthSlider);
        
        panelContent.appendChild(fontSizeContainer);
        panelContent.appendChild(lineHeightContainer);
        panelContent.appendChild(contentWidthContainer);
        
        panel.appendChild(panelContent);
        document.body.appendChild(panel);
        
        return {
            panel,
            fontSizeSlider,
            lineHeightSlider,
            contentWidthSlider,
            fontSizeLabel,
            lineHeightLabel,
            contentWidthLabel
        };
    }

    // 应用文本样式
    function applyTextStyles(fontSize, lineHeight, contentWidth) {
        // 获取聊天内容的各个元素
        const chatDetailContent = document.querySelector('.chat-detail-content');
        const chatContentContainer = document.querySelector('.chat-content-container');
        const chatContentList = document.querySelector('.chat-content-list');
        const segmentContainers = document.querySelectorAll('.segment-container');
        const segmentContents = document.querySelectorAll('.segment-content');
        
        // 应用内容宽度
        if (chatDetailContent) {
            chatDetailContent.style.width = `${contentWidth}%`;
            chatDetailContent.style.maxWidth = `${contentWidth}%`;
            chatDetailContent.style.margin = '0 auto';
        }
        
        // 强制设置聊天容器宽度
        if (chatContentContainer) {
            chatContentContainer.style.width = '100%';
            chatContentContainer.style.maxWidth = '100%';
        }
        
        // 设置聊天内容列表宽度
        if (chatContentList) {
            chatContentList.style.width = '100%';
            chatContentList.style.maxWidth = '100%';
        }
        
        // 设置每个聊天段落容器的宽度
        segmentContainers.forEach(container => {
            container.style.width = '100%';
            container.style.maxWidth = '100%';
        });
        
        // 设置每个聊天内容的宽度
        segmentContents.forEach(content => {
            content.style.width = `${contentWidth}%`;
            content.style.maxWidth = `${contentWidth}%`;
        });
        
        // 应用文本样式到所有可能的聊天内容元素
        const styleElements = [
            '.markdown', 
            '.paragraph', 
            '.user-content',
            '.segment-content-box',
            '.markdown-container',
            '.table-container',
            'ul li',
            'ol li',
            'h3', 'h4',
            '.segment-code-inline',
            '.segment-generate-tip',
            '.katex-display'
        ];
        
        styleElements.forEach(selector => {
            const elements = document.querySelectorAll(selector);
            elements.forEach(element => {
                element.style.fontSize = `${fontSize}px`;
                element.style.lineHeight = lineHeight;
            });
        });
        
        // 特别处理代码块和表格
        const codeBlocks = document.querySelectorAll('pre, code, .table-container table');
        codeBlocks.forEach(block => {
            block.style.fontSize = `${fontSize}px`;
        });
        
        // 特别处理表格内的所有元素
        const tableElements = document.querySelectorAll('.table-container table, .table-container th, .table-container td, .table-container tr, .table-container thead, .table-container tbody, .table-container caption');
        tableElements.forEach(element => {
            element.style.fontSize = `${fontSize}px`;
            element.style.lineHeight = lineHeight;
        });
        
        // 确保表格内的所有文本内容也能被正确缩放
        const tableTextElements = document.querySelectorAll('.table-container *');
        tableTextElements.forEach(element => {
            if (element.childNodes && element.childNodes.length > 0) {
                element.style.fontSize = `${fontSize}px`;
                element.style.lineHeight = lineHeight;
            }
        });
        
        // 特别处理markdown容器
        const markdownContainers = document.querySelectorAll('.markdown-container');
        markdownContainers.forEach(container => {
            container.style.width = '100%';
            container.style.maxWidth = '100%';
        });
        
        // 处理内部内容盒子
        const contentBoxes = document.querySelectorAll('.segment-content-box');
        contentBoxes.forEach(box => {
            box.style.width = '100%';
            box.style.maxWidth = '100%';
        });
    }

    // 管理面板的显示和隐藏
    function managePanelVisibility(panel) {
        let hideTimeout;
        
        // 显示面板
        function showPanel() {
            clearTimeout(hideTimeout);
            panel.classList.remove('collapsed');
        }
        
        // 隐藏面板
        function hidePanel() {
            panel.classList.add('collapsed');
        }
        
        // 鼠标移入面板时显示
        panel.addEventListener('mouseenter', showPanel);
        
        // 鼠标移出面板时，5秒后隐藏
        panel.addEventListener('mouseleave', () => {
            hideTimeout = setTimeout(hidePanel, 5000);
        });
        
        // 点击小圆点时显示面板
        panel.addEventListener('click', (e) => {
            if (panel.classList.contains('collapsed')) {
                showPanel();
            }
        });
        
        // 页面加载后显示8秒，然后隐藏
        setTimeout(hidePanel, 8000);
    }

    // 初始化
    function init() {
        // 等待DOM加载完成
        const checkInterval = setInterval(() => {
            if (document.querySelector('.chat-content-container')) {
                clearInterval(checkInterval);
                
                const controls = createControlPanel();
                
                // 初始化应用样式
                applyTextStyles(
                    controls.fontSizeSlider.value,
                    controls.lineHeightSlider.value,
                    controls.contentWidthSlider.value
                );
                
                // 初始化应用表格样式
                applyTableStyles(
                    controls.fontSizeSlider.value,
                    controls.lineHeightSlider.value
                );
                
                // 监听滑块变化
                controls.fontSizeSlider.addEventListener('input', (e) => {
                    const value = e.target.value;
                    controls.fontSizeLabel.querySelector('.slider-value').textContent = `${value}px`;
                    applyTextStyles(value, controls.lineHeightSlider.value, controls.contentWidthSlider.value);
                    
                    // 额外处理表格元素
                    applyTableStyles(value, controls.lineHeightSlider.value);
                    
                    // 自动保存设置
                    saveSettings(value, controls.lineHeightSlider.value, controls.contentWidthSlider.value);
                });
                
                controls.lineHeightSlider.addEventListener('input', (e) => {
                    const value = e.target.value;
                    controls.lineHeightLabel.querySelector('.slider-value').textContent = value;
                    applyTextStyles(controls.fontSizeSlider.value, value, controls.contentWidthSlider.value);
                    
                    // 额外处理表格元素
                    applyTableStyles(controls.fontSizeSlider.value, value);
                    
                    // 自动保存设置
                    saveSettings(controls.fontSizeSlider.value, value, controls.contentWidthSlider.value);
                });
                
                controls.contentWidthSlider.addEventListener('input', (e) => {
                    const value = e.target.value;
                    controls.contentWidthLabel.querySelector('.slider-value').textContent = `${value}%`;
                    applyTextStyles(controls.fontSizeSlider.value, controls.lineHeightSlider.value, value);
                    
                    // 自动保存设置
                    saveSettings(controls.fontSizeSlider.value, controls.lineHeightSlider.value, value);
                });
                
                // 管理面板显示/隐藏
                managePanelVisibility(controls.panel);
                
                // 监听窗口大小变化，重新应用样式
                window.addEventListener('resize', () => {
                    applyTextStyles(
                        controls.fontSizeSlider.value,
                        controls.lineHeightSlider.value,
                        controls.contentWidthSlider.value
                    );
                    
                    // 额外处理表格元素
                    applyTableStyles(controls.fontSizeSlider.value, controls.lineHeightSlider.value);
                });
                
                // 监听DOM变化，确保新加载的聊天内容也应用样式
                const observer = new MutationObserver(() => {
                    applyTextStyles(
                        controls.fontSizeSlider.value,
                        controls.lineHeightSlider.value,
                        controls.contentWidthSlider.value
                    );
                    
                    // 额外处理表格元素
                    applyTableStyles(controls.fontSizeSlider.value, controls.lineHeightSlider.value);
                });
                
                observer.observe(document.querySelector('.chat-content-list'), {
                    childList: true,
                    subtree: true
                });
            }
        }, 500);
    }
    
    // 专门处理表格样式的函数
    function applyTableStyles(fontSize, lineHeight) {
        // 获取所有表格相关元素
        const tableSelectors = [
            '.table-container', 
            '.table-container table', 
            '.table-container th', 
            '.table-container td', 
            '.table-container tr', 
            '.table-container thead', 
            '.table-container tbody', 
            '.table-container caption',
            '.table-container p',
            '.table-container span',
            '.table-container div',
            '.table-container code',
            '.table-container pre',
            '.table-container strong',
            '.table-container em',
            '.table-container a'
        ];
        
        // 为每个选择器应用样式
        tableSelectors.forEach(selector => {
            const elements = document.querySelectorAll(selector);
            elements.forEach(element => {
                element.style.fontSize = `${fontSize}px`;
                element.style.lineHeight = lineHeight;
            });
        });
        
        // 使用CSS选择器直接添加内联样式
        const styleElement = document.createElement('style');
        styleElement.textContent = `
            .table-container * {
                font-size: ${fontSize}px !important;
                line-height: ${lineHeight} !important;
            }
        `;
        
        // 移除旧的样式元素（如果存在）
        const oldStyle = document.getElementById('table-style-element');
        if (oldStyle) {
            oldStyle.remove();
        }
        
        // 添加新的样式元素
        styleElement.id = 'table-style-element';
        document.head.appendChild(styleElement);
    }

    // 启动脚本
    init();
})();
